package com.soul.common.utils;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 数组集合工具类
 * @author shiwenshuai
 * @version 1.0
 * @date 2022/11/22 15:36
 */
public class ListUtil {

    /**
     * 集合转换
     * @param list 转化集合
     * @param fun 转化的字段
     * @param distinct 是否去重
     * @return
     */
    public static <T,U> List<U> toValueList(List<T> list, Function<T, U> fun, boolean distinct) {
        Stream<U> stream = list.stream().map(fun);
        if (distinct){
            stream = stream.distinct();
        }
        return stream.collect(Collectors.toList());
    }

    /**
     * 集合转换 (默认不去重)
     * @param list 转化集合
     * @param fun 转化的字段
     * @return
     */
    public static <T,U> List<U> toValueList(List<T> list, Function<T, U> fun) {
        return toValueList(list,fun,false);
    }

    public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> fun) {
        if (!ObjectUtils.isEmpty(list) && !ObjectUtils.isEmpty(fun)) {
            return list.stream().collect(Collectors.toMap(fun,t->t));
        }
        return new LinkedHashMap<>();
    }

    public static <K, V> Map<K, List<V>> listToMapList(List<V> list, Function<V, K> fun) {
        if (!ObjectUtils.isEmpty(list) && !ObjectUtils.isEmpty(fun)) {
            return list.stream().collect(Collectors.groupingBy(fun));
        }
        return new LinkedHashMap<>();
    }
    public static <K, V , K2> Map<K, Map<K2,V>> listToMapListMap(List<V> list, Function<V, K> fun, Function<V, K2> fun2) {
        if (!ObjectUtils.isEmpty(list) && !ObjectUtils.isEmpty(fun)) {
            return list.stream().collect(Collectors.groupingBy(fun,Collectors.toMap(fun2,t->t)));
        }
        return new LinkedHashMap<>();
    }

    public static <T,U>  Set<U> toValueSet(List<T> list, Function<T, U> fun) {
        if (ObjectUtil.isNotEmpty(list)){
            return list.stream().map(fun).collect(Collectors.toSet());
        }
        return null;
    }
}
